package com.dailyblue.java.cloud.security.filter;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class IsLoginFilter extends BasicAuthenticationFilter {
    private AuthenticationManager authenticationManager;

    private StringRedisTemplate stringRedisTemplate;

    public IsLoginFilter(AuthenticationManager authenticationManager, StringRedisTemplate stringRedisTemplate) {
        super(authenticationManager);
        this.authenticationManager = authenticationManager;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /*
    验证用户是否登陆
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("进入验证用户是否登陆的过滤器");
        // 接收用户传递过来的token
        String token = request.getHeader("token");
        log.info("用户传递的token是：{}", token);
        Object result = stringRedisTemplate.opsForValue().get("NAME");
        if (result != null) {
            List<GrantedAuthority> list = new ArrayList<>();
            GrantedAuthority g1 = new SimpleGrantedAuthority("admin");
            list.add(g1);
            UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(1, token, list);
            log.info("封装后的信息是：{}", upat);
            // 这个代表用户可以验证通过了
            // 有权限，则放入权限上下文中
            SecurityContextHolder.getContext().setAuthentication(upat);
        }
        chain.doFilter(request, response);
    }
}
